package com.apexsoft.monitor.front.console.user.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.support.Result;
import com.apexsoft.front.common.utils.JsonResult;
import com.apexsoft.monitor.front.console.user.dao.MenuDao;
import com.apexsoft.monitor.front.console.user.dao.UserDao;
import com.apexsoft.monitor.front.console.user.om.Menu;
import com.apexsoft.monitor.front.console.user.om.User;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


@Service("consoleUserService")
public class UserService {
	
	@Autowired
	private UserDao userDao = null;
	
	@Autowired
	private MenuDao menuDao = null;
	
	/**
	 * 用户登陆验证
	 * @param loginId
	 * @param password
	 * @return
	 */
	public JSONObject userLogin(String loginId,String password)
	{
		User user = null;
		try{
			user = userDao.getUserByLoginId(loginId);
			if(user!=null){
				if(user.getPassword().equalsIgnoreCase(password)){
					JSONObject userObj = new JSONObject();
					userObj.put("id", user.getId());
					userObj.put("loginId", user.getLoginId());
					userObj.put("name", user.getName());
					userObj.put("usertype", user.getUsertype());
					return new JsonResult(true,"登陆成功").putObject(userObj).getResult();
				}
				else{
					return new JsonResult(false,"用户名或者密码错误").getResult();
				}
			}
			else{
				return new JsonResult(false,"sorry！用户名不存在").getResult();
			}
		}
		catch(Exception e){
			return new JsonResult().getExceptionResult(e);
		}
	}
	
	/**
	 * 修改系统用户密码
	 * @param u
	 * @return oldPwd
	 */
	public JSONObject uptSystemPwd(User u,String oldPwd) {
		try{
			if(userDao.getUserByLoginId(u.getLoginId()).getPassword().equals(oldPwd)){
				userDao.updateById(u);
				return new JsonResult(true,"修改系统用户密码成功！").getResult();
			}else{
				return new JsonResult(false,"旧密码输入错误！").getResult();
			}
		}catch(Exception e){
			return new JsonResult().getExceptionResult(e);
		}
	}
	/**
	 * 修改系统用户信息
	 * @param u
	 */
	public JSONObject uptSystemInfo(User u) {
		try{
			userDao.updateById(u);
			return new JsonResult(true,"修改系统用户密码成功！").getResult();
		}catch(Exception e){
			return new JsonResult().getExceptionResult(e);
		}
	}
	
	/**
	 * 获取系统用户信息
	 * @param loginId
	 */
	public JSONObject getSystemUser(String loginId) {
		User user = null;
		try{
			user = userDao.getUserByLoginId(loginId);
			if(user!=null){
				JSONObject userObj = new JSONObject();
				userObj.put("id", user.getId());
				userObj.put("loginId", user.getLoginId());
				userObj.put("name", user.getName());
				userObj.put("menuIds", user.getMenuIds());
				userObj.put("usertype", user.getUsertype());
				userObj.put("password", user.getPassword());
				userObj.put("attr", user.getAttr());
				return new JsonResult(true,"获取系统用户信息成功").putObject(userObj).getResult();
			}
			else{
				return new JsonResult(false,"sorry！用户名不存在").getResult();
			}
		}
		catch(Exception e){
			return new JsonResult().getExceptionResult(e);
		}
	}

	//获取系统维护人员列表
	public JSONObject getSystemUserList() {
		List<User> userList = new ArrayList<User>();
		JSONObject listObj = new JSONObject();
		try{
			userList = userDao.selectList(new EntityWrapper<User>());
			listObj.put(Result.RECORDS, userList);
			listObj.put(Result.CODE, Result.SC_0001);
			listObj.put(Result.NOTE, "查询成功");
			listObj.put(Result.COUNT, userList.size());
		}catch(Exception e){
			listObj.put(Result.CODE, Result.EC_1000);
			listObj.put(Result.NOTE, "查询运维人员列表异常：" + e.getMessage());

		}
		return listObj;
	}

	//添加系统运维人员
	public JSONObject addSystemUser(User user) {
		// TODO Auto-generated method stub
		int result = 0;
		try{
			User u = userDao.getUserByLoginId(user.getLoginId());
			if(u==null){
				result = userDao.insert(user);
				if(result>0){
					return new JsonResult(true,"添加运维人员成功！").getResult();
				}else{
					return new JsonResult(false,"添加运维人员失败！").getResult();
				}
			}else{
				return new JsonResult(false,"该登录ID已存在，不能重复添加！").getResult();
			}
		}catch(Exception e){
			return new JsonResult(false,e.getMessage()).getExceptionResult(e);
		}
	}

	//删除系统维护人员
	public JSONObject delSystemUser(String id) {
		try{
			userDao.deleteById(Long.parseLong(id));
			return new JsonResult(true,"删除系统维护人员成功！").getResult();
		}catch(Exception e){
			return new JsonResult().getExceptionResult(e);
		}
	}
	
	public JSONArray getSystemMenuList(String loginId) throws Exception {
		
		User user = userDao.getUserByLoginId(loginId);
		return getSystemMenuListByIds(user.getMenuIds());
	}
	
	//根据菜单id数获取console菜单列表
	public JSONArray getSystemMenuListByIds(String ids) {
		List<Menu> menuList = menuDao.selectList(new EntityWrapper<Menu>());
		JSONArray jsonArray = new JSONArray();
		try {
			for (Menu menu : menuList) {
				JSONObject jsonObject = new JSONObject();
				if(menu.getPid()!=0){
					continue;
				}else{
					jsonObject.put("id", menu.getId());
					jsonObject.put("menuType", menu.getMenuType());
					jsonObject.put("menuIndex", menu.getMenuIndex());
					jsonObject.put("text", menu.getName());
					jsonObject.put("url", StringUtils.isBlank(menu.getUrl())?"":menu.getUrl());
					jsonObject.put("iconClass", StringUtils.isBlank(menu.getIconClass())?"":menu.getIconClass());
					if(ids!=null&&ids.length()>0){
						String[] menuIds = ids.split(",");
						for(int i=0;i<menuIds.length;i++){
							if(menu.getId()==Integer.valueOf(menuIds[i])){
								jsonObject.put("selected", true);
							}
						}
						JSONArray childMenu = getChildMenu(menuList,menu,menuIds);
//						JSONObject childMenu = getChildMenu2(menuList,menu,menuIds);
						jsonObject.put("children",sortJsonArrayByKey(childMenu,"menuIndex"));
						if (childMenu==null || childMenu.size()<0) {
							if (jsonObject.containsKey("selected") && jsonObject.getBooleanValue("select")) {
								jsonObject.put("checked", true);
							}
						}
					}else{
						jsonObject.put("children",sortJsonArrayByKey(getChildMenu(menuList,menu,new String[0]),"menuIndex"));
					}
					jsonArray.add(jsonObject);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return jsonArray;
	}

	public JSONArray getChildMenu(List<Menu> menuList,Menu menu,String[] menuIds){
		JSONArray jsonArray = new JSONArray();
		for (Menu tmpmenu : menuList) {
			JSONObject jsonObject = new JSONObject();
			if(tmpmenu.getPid()==menu.getId()){
				jsonObject.put("id", tmpmenu.getId());
				jsonObject.put("menuType", tmpmenu.getMenuType());
				jsonObject.put("menuIndex", tmpmenu.getMenuIndex());
				jsonObject.put("text", tmpmenu.getName());
				jsonObject.put("url", tmpmenu.getUrl());
				jsonObject.put("iconClass", StringUtils.isBlank(tmpmenu.getIconClass())?"":tmpmenu.getIconClass());
				for(int i=0;i<menuIds.length;i++){
					if(tmpmenu.getId()==Integer.valueOf(menuIds[i])){
						jsonObject.put("checked", true);
						jsonObject.put("selected", true);
					}
				}
				JSONArray childrenArray = getChildMenu(menuList,tmpmenu,menuIds);
				jsonObject.put("children",sortJsonArrayByKey(childrenArray,"menuIndex"));
				jsonArray.add(jsonObject);
			}
		}
		return jsonArray;
	}

	private JSONArray sortJsonArrayByKey(JSONArray array,String key){
		JSONArray tempArray = new JSONArray();
		List<JSONObject> list = new ArrayList<JSONObject> ();
		for (int i = 0; i < array.size(); i++) {
			list.add(array.getJSONObject(i));
		}
		Collections.sort(list, new Comparator<Object>() {
			public int compare(Object m1,Object m2) {
				JSONObject j1 = (JSONObject)m1;
				JSONObject j2 = (JSONObject)m2;
				return j1.getIntValue(key)-j2.getIntValue(key);
			};
		});
		for (int i = 0; i < list.size(); i++) {
			tempArray.add(list.get(i));
		}
		return tempArray;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject updatePermission(String loginId, String menuIds) {
		try{
			User user = userDao.getUserByLoginId(loginId);
			if(menuIds.length()>0){
				String[] idsStrings = menuIds.split(",");
				List<Menu> menuList = menuDao.selectList(new EntityWrapper<Menu>());
				List tmp = new ArrayList();
				for (Menu menu : menuList) {
					for(int i=0;i<idsStrings.length;i++){
						if(menu.getId()==Integer.valueOf(idsStrings[i])){
							tmp.add(menu.getId());
						}
					}
				}
				
				if(tmp.size()==idsStrings.length&&user!=null){
					user.setMenuIds(menuIds);
					userDao.updateById(user);
					return new JsonResult(true,"修改系统用户权限成功！").getResult();
				}else{
					return new JsonResult(false,"修改系统用户权限错误！").getResult();
				}
			}else{
				if(user!=null){
					user.setMenuIds("");
					userDao.updateById(user);
					return new JsonResult(true,"修改系统用户权限成功！").getResult();
				}else{
					return new JsonResult(false,"修改系统用户权限错误！").getResult();
				}
				
			}
			
		}catch(Exception e){
			return new JsonResult().getExceptionResult(e);
		}
	}
	
	public JSONObject listByPageForEasyui (int page, int pageCount) {
		try{
			User user = new User();
			Page<User> pageDdApp = new Page<User>(page, pageCount);
			EntityWrapper<User> entityWrapper = new EntityWrapper<User>(user);
			entityWrapper.orderBy("id", false);
			List<User> ddApps = userDao.selectPage(pageDdApp, entityWrapper);
			int count = userDao.selectCount(user);
			JSONObject obj = new JSONObject();
			obj.put(Result.TOTAL, count);
			obj.put("rows", ddApps);
			return new JsonResult(true,"获取用户信息列表成功！").putObject(obj).getResult();
		}catch(Exception e){
			return new JsonResult().getExceptionResult(e);
		}
	}

	public User getUserById(long id) {
		return userDao.selectById(id);
	}
}
